//
//  AddressBook.m
//  通讯录
//
//  Created by 李世友 on 16/4/28.
//  Copyright © 2016年 李世友. All rights reserved.
//

#import "AddressBook.h"
#import "Contact.h"
@class Contact;



@interface AddressBook()
@property(nonatomic,retain)NSMutableDictionary *mDic;
@end



@implementation AddressBook
-(instancetype)init
{
    self = [super init];
    if (self)
    {
        _mDic  =[NSMutableDictionary dictionary];
    }
    return self;
}
-(NSString *)firstCharacter:(NSString *)string
{
    return [[string substringToIndex:1] uppercaseString];
    
}
-(void)addContact:(Contact *)con
{
    NSMutableArray *mArr = [self.mDic objectForKey:con.groupName];//先找
    if (mArr == nil)//找不到
    {
        NSMutableArray *m = [NSMutableArray array];
        [m addObject:con];
        [self.mDic setObject:con forKey:con.groupName];
    }
    else
    {
        [mArr addObject:con];
    }
}
-(void)deleteContactForName:(NSString *)name
{
    NSMutableArray *a = [_mDic objectForKey:[self firstCharacter:name]];//[self firstCharacter:name]调用本类的方法,用self:返回的是一个字符串类
    NSMutableArray *arrOfTemp  = [NSMutableArray array];
    for (Contact *con in a)
    {
        if ([con.name isEqualToString:name])
        {
            [arrOfTemp addObject:con];
        }
    }
    [a removeObjectsInArray:arrOfTemp];
}
- (NSArray<Contact *> *)showAllContactForGroup:(NSString *)string
{
    NSMutableArray *mArr = [self.mDic objectForKey:[self firstCharacter:string]];
    //按照联系人姓名升序排序;
    NSArray *arrOfSort = [mArr sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        Contact *con1 = (Contact *)obj1;
        Contact *con2 = (Contact *)obj2;
        return  [con1.name compare:con2.name];//这是一个函数 返回值是NSComparisonResult,两个id类型的参数 (^代表block 是代码块的意思) 方法当中是两个两个的比较
    }];
    return arrOfSort;
}
@end
